﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Data;
using CreditAgricole.Application;
using CreditAgricole.Framework;

namespace CreditAgricole.PageCodeBehind
{
    [ToolboxItemAttribute(false)]
    public class MepViewsWebPart : WebPart
    {
        #region Properties

        /// <summary>
        /// Views menu
        /// </summary>
        private Menu viewsMenu;

        /// <summary>
        /// Views menu
        /// </summary>
        public Menu ViewsMenu
        {
            get { return viewsMenu; }
            set { viewsMenu = value; }
        }

        /// <summary>
        /// Web id where MEP list is installed
        /// </summary>
        public Guid WebId;

        /// <summary>
        /// Site id
        /// </summary>
        public Guid SiteId;

        #endregion

        private List<VOMep> allMepObjs;

        private int mepCounter;

        /// <summary>
        /// Control init event
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            AddViewsMenu();
        }

        /// <summary>
        /// Control Loading event
        /// </summary>
        /// <param name="e">Even related to loading control</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            mepCounter = 0;
            GetDataBindToGridview();
        }

        /// <summary>
        /// Add the views menu
        /// </summary>
        private void AddViewsMenu()
        {
            ViewsMenu = (Menu)this.Page.LoadControl("~/_controltemplates/CreditAgricole.CustomControl/Menu.ascx");
            Panel pnlMenu = new Panel();
            pnlMenu.CssClass = "header";
            pnlMenu.Controls.Add(ViewsMenu);
            Controls.Add(pnlMenu);
        }

        /// <summary>
        /// Get data to bind with gridview and call method BindToGridView
        /// </summary>
        private void GetDataBindToGridview()
        {
            Label viewTitle = new Label();
            Panel pnlViewTitle = new Panel();
            pnlViewTitle.CssClass = "viewTitleclass";
            pnlViewTitle.Controls.Add(viewTitle);
            List<VOMep> selectedItems = new List<VOMep>();
            switch (ViewsMenu.SelectedMenu)
            {
                case Constants.ElementsMenu.MyCreatedTasksTag:
                    {
                        viewTitle.Text = "Mes demandes effectuées";
                        switch(ViewsMenu.SelectedCritiria)
                        {
                            case Constants.ElementsMenuCritiria.FirstCritiria:
                                selectedItems = DataMep.GetCreatedTasksByWorkflowStatus(SiteId, WebId, 
                                                                            Constants.ChangingListTitle, 
                                                                            SPContext.Current.Web.CurrentUser.ID, 
                                                                            "16", Constants.CamlQueryOperator.Equal);
                                break;
                            case Constants.ElementsMenuCritiria.SecondCritiria:
                                selectedItems = DataMep.GetCreatedTasksByWorkflowStatus(SiteId, WebId, 
                                                                            Constants.ChangingListTitle, 
                                                                            SPContext.Current.Web.CurrentUser.ID, 
                                                                            "16", Constants.CamlQueryOperator.NotEqual);
                                break;
                            default:
                                selectedItems = DataMep.GetCreatedTasksByWorkflowStatus(SiteId, WebId, 
                                                                            Constants.ChangingListTitle, 
                                                                            SPContext.Current.Web.CurrentUser.ID, 
                                                                            "16", Constants.CamlQueryOperator.Equal);
                                break;
                        }
                        break;
                    }
                case Constants.ElementsMenu.TasksToBeValidatedTag:
                    {
                        viewTitle.Text = "Demandes à valider";
                        switch (ViewsMenu.SelectedCritiria)
                        {
                            case Constants.ElementsMenuCritiria.FirstCritiria:
                                selectedItems = DataMep.GetTasksAssignedToMeByWorkflowStatus(SiteId, WebId, 
                                                                                    Constants.ChangingListTitle,
                                                                                    SPContext.Current.Web.CurrentUser.ID,
                                                                                    Constants.CamlQueryOperator.Equal,
                                                                                    "2", Constants.CamlQueryOperator.Equal);
                                break;
                            case Constants.ElementsMenuCritiria.SecondCritiria:
                                selectedItems = DataMep.GetTasksAssignedToMeByWorkflowStatus(SiteId, WebId, 
                                                                                    Constants.ChangingListTitle,
                                                                                    SPContext.Current.Web.CurrentUser.ID,
                                                                                    Constants.CamlQueryOperator.NotEqual,
                                                                                    "2", Constants.CamlQueryOperator.Equal);
                                break;
                            default:
                                selectedItems = DataMep.GetTasksAssignedToMeByWorkflowStatus(SiteId, WebId, 
                                                                                    Constants.ChangingListTitle,
                                                                                    SPContext.Current.Web.CurrentUser.ID,
                                                                                    Constants.CamlQueryOperator.Equal,
                                                                                    "2", Constants.CamlQueryOperator.Equal);
                                break;
                        }
                        break;
                    }
                case Constants.ElementsMenu.ValidatedTasksTag:
                    {
                        viewTitle.Text = "Les demandes validées";
                        switch (ViewsMenu.SelectedCritiria)
                        {
                            case Constants.ElementsMenuCritiria.FirstCritiria:
                                {
                                    selectedItems = DataMep.GetItemsByProdStatus(SiteId, WebId, 
                                                                                Constants.ChangingListTitle, 
                                                                                "Pas en production", Constants.CamlQueryOperator.Equal);
                                    break;
                                }
                            case Constants.ElementsMenuCritiria.SecondCritiria:
                                {
                                    selectedItems = DataMep.GetItemsByProdStatus(SiteId, WebId, 
                                                                                Constants.ChangingListTitle, 
                                                                                "Pas en production", Constants.CamlQueryOperator.NotEqual);
                                    break;
                                }
                            default :
                                {
                                    selectedItems = DataMep.GetItemsByProdStatus(SiteId, WebId, 
                                                                                Constants.ChangingListTitle, 
                                                                                "Pas en production", Constants.CamlQueryOperator.Equal);
                                    break;
                                }
                        }
                        break;
                    }
                case Constants.ElementsMenu.AllTasksTag:
                    {
                        viewTitle.Text = "Toutes les demandes";
                        selectedItems = DataMep.GetMepObj(SiteId, WebId, Constants.ChangingListTitle);
                        break;
                    }
                case Constants.ElementsMenu.AllCreatedTasksTag:
                    {
                        viewTitle.Text = "Toutes les demandes créées (validées ou non) sur les 6 derniers mois";
                        break;
                    }
            }
            if (selectedItems.Count > 0)
            {
                BindToGridView(selectedItems);
            }
        }

        #region Tools Methods

        private void InsertDataInTable(List<VOMep> selectedItems, DataTable table)
        {
            foreach (VOMep result in selectedItems)
            {
                DataRow row = table.Rows.Add();
                row["Title"] = result.Title;
                row["Name"] = result.Name;
                row["Created"] = result.Created;
                row["Author"] = result.Author;
                row["Workflow"] = result.Workflow;
                row["Current Approver"] = result.CurrentApprover;
                row["Status"] = result.MepStatus;
            }
        }

        private void CreateColumns(DataTable table)
        {
            table.Columns.Add("Title", typeof(string));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Created", typeof(string));
            table.Columns.Add("Author", typeof(string));
            table.Columns.Add("Workflow", typeof(string));
            table.Columns.Add("Current Approver", typeof(string));
            table.Columns.Add("Status", typeof(string));
        }

        private SPBoundField CreateBoundField(string fieldName)
        {
            SPBoundField boundField = new SPBoundField();
            boundField.HeaderText = fieldName;
            boundField.DataField = fieldName;
            boundField.ItemStyle.Wrap = true;
            return boundField;
        }

        /// <summary>
        /// Create a gridview, bind all data and disply it
        /// </summary>
        /// <param name="selectedItems">Data to bind in gridview</param>
        private void BindToGridView(List<VOMep> selectedItems)
        {
            allMepObjs = selectedItems;
            Panel pnlGridview = new Panel();
            pnlGridview.CssClass = "panelView";

            GridView gridView = new GridView();
            gridView.CssClass = "mGrid";
            gridView.AllowPaging = true;
            gridView.PageSize = 30;
            gridView.PagerStyle.CssClass = "pagerclass";
            DataTable table = new DataTable();
            CreateColumns(table);
            InsertDataInTable(selectedItems, table);
            gridView.Columns.Add(CreateBoundField("Title"));
            gridView.Columns.Add(CreateBoundField("Name"));
            gridView.Columns.Add(CreateBoundField("Created"));
            gridView.Columns.Add(CreateBoundField("Author"));
            gridView.Columns.Add(CreateBoundField("Workflow"));
            gridView.Columns.Add(CreateBoundField("Current Approver"));
            gridView.Columns.Add(CreateBoundField("Status"));
            gridView.AutoGenerateColumns = false; 
            
            pnlGridview.Controls.Add(gridView);
            Controls.Add(pnlGridview);

            gridView.RowDataBound += new GridViewRowEventHandler(gview_OnInsertRow);
            gridView.PageIndexChanging += new GridViewPageEventHandler(gview_OnPageIndexChanging);
            gridView.DataSource = table.DefaultView;
            gridView.DataBind();
        }



        /// <summary>
        /// Event to call when a datarow is created. It adds a hidden row where further details are stored
        /// </summary>
        /// <param name="sender">Gridview where data is inserted</param>
        /// <param name="e">Event Handler</param>
        protected void gview_OnInsertRow(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                case DataControlRowType.DataRow:
                    {
                        GridView gView = (GridView)sender;
                        int colSpan = gView.Columns.Count;
                        TableCell tCell = new TableCell();
                        tCell.Attributes["ColSpan"] = MappingTool.CatchNull(colSpan);

                        Panel pnlDetail = new Panel();
                        pnlDetail.CssClass = "detailedPanel";
                        tCell.Controls.Add(pnlDetail);
                        Label lblEntities = new Label();
                        lblEntities.Text = "Entités:\n";

                        VOMep currentMepObj = allMepObjs[mepCounter];
                        foreach (string entity in currentMepObj.Entity)
                        {
                            lblEntities.Text += entity;
                        }
                        pnlDetail.Controls.Add(lblEntities);

                        GridViewRow gRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                        gRow.CssClass = "hiddenRow";
                        gRow.Cells.Add(tCell);

                        Table tbl = (Table)e.Row.Parent;
                        tbl.Controls.AddAt(gView.Controls[0].Controls.Count, gRow);
                        mepCounter++;
                        break;
                    }
                case DataControlRowType.Pager:
                    {
                        TableCell cell = e.Row.Cells[0];
                        if (cell.Controls[0] != null)
                        {
                            TableRow row = cell.Controls[0].Controls[0] as TableRow;
                            row.CssClass = "pagerclass";
                        }
                        break;
                    }
            }
        }

        protected void gview_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView gView = (GridView)sender;
            gView.PageIndex = e.NewPageIndex;
            gView.DataBind();
        }

        #endregion
    }
}
